<template>
  <el-upload
    class="upload-demo"
    drag
    multiple
    :action="uploadUrl"
    :headers="headers"
    :before-upload="beforeUpload"
    :on-success="handleUploadSuccess"
  >
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    <template #tip>
      <div class="el-upload__tip">
        上传文件只能是 JPG/PNG/BMP/PDF 格式，且单文件大小不超过2MB!
      </div>
    </template>
  </el-upload>
</template>

<script>
import { ref, computed } from "vue";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";
export default {
  setup() {
    const store = useStore();
    const headers = computed(() => {
      return {
        Authorization: store.state.token,
        ContentType: "multipart/form-data",
      };
    });
    const uploadUrl = ref("/api/invoice/info");
    const handleUploadSuccess = (res, file) => {
      console.log("response data:", res.data);
      console.log("file-type:", file.type);
      //   URL.createObjectURL(file.raw);
    };
    const beforeUpload = (file) => {
      console.log("file type:", file.type);
      const validFormat =
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/bmp" ||
        file.type === "application/pdf";
      const validFileSize = file.size / 1024 / 1024 < 2;

      if (!validFormat) {
        ElMessage.error("上传文件只能是 JPG/PNG/BMP/PDF 格式!");
      }
      if (!validFileSize) {
        ElMessage.error("上传文件大小不能超过 2MB!");
      }
      return validFormat && validFileSize;
    };
    return { uploadUrl, handleUploadSuccess, beforeUpload, headers };
  },
};
</script>

<style>
</style>